package service

import (
	"context"
	"gitee.com/WisdomClassroom/Course/glb"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"google.golang.org/grpc/metadata"
)

func (s *Service) DeleteCourse(ctx context.Context, request *pb.DeleteCourseRequest) (*pb.DeleteCourseResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.DeleteCourseResponse{Status: &pb.ResponseStatus{
			Code: core.ResponseStatusCodeNotAuth, Message: err.Error(),
		}}, nil
	}

	course := &models.Course{UUID: request.GetUUID()}

	if !token.IsManager {
		managers := make([]models.User, 0, 1)
		err = glb.DB.Model(course).Association("Managers").Find(&managers, "manager_id = ?", token.AccountID)
		if err != nil {
			glb.Logger.Error(err.Error())
			return deleteCourseRespSvrErr, nil
		}
		if len(managers) == 0 {
			return &pb.DeleteCourseResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeNotAuth,
				Message: "用户没有权限",
			}}, nil
		}
	}

	err = glb.DB.Delete(course).Error
	if err != nil {
		glb.Logger.Error(err.Error())
		return deleteCourseRespSvrErr, nil
	}

	return &pb.DeleteCourseResponse{
		Status: &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
	}, nil
}
